package
{
	import com.adobe.serialization.json.JSON;
	import com.happystreet.GlobalGameConstants;
	import com.happystreet.develop.DeveloperPreferences;
	import com.happystreet.interfaces.IApplication;
	import com.happystreet.interfaces.ILoader;
	import com.happystreet.loader.LoadingQueue;
	import com.happystreet.loader.LoadingQueueItem;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	
	/**
	 * 游戏加载壳
	 * @author Liseen
	 * 
	 */
	[SWF(width="760", height="620", backgroundColor="#000000")]
	public class StreetGameLoader extends Sprite implements ILoader
	{
		
		[Embed(source="uiLib.swf", symbol="MyStreetLoader_LoaderNew")]
		public static var MyStreetLoader_LoaderNew:Class;
		
		public static const DEFAULT_FRAMERATE:int=30;
		//所有资源总字节
		private const dataLoadedTotal:int = 8400000;
		
		private var LoaderNewClass:Class;
		private var _loaderNew:Sprite;
		private var _loaderAssetsList:Array;
		
		private var _loadingQueue:LoadingQueue;
		private var _gameDataUrlList:Vector.<String>;
		private var _dataLoadedSize:Number=0;
		private var _flashvars:Object;
		
		private  var _partsConfigData:String;
		private  var _materialsConfigData:String;
		private  var _shopsConfigData:String;
		private  var _goodsConfigData:String;
		private  var _textConfigData:String;
		private  var _customersConfigData:String;
		private  var _josConfigData:String;
		private  var _assetsConfigData:String;
		private  var _giftConfigData:String;
		private  var _achievementsConfigData:String;
		private  var _histroyConfigData:String;
		private  var _missionConfigData:String;
		private  var _storeConfigData:String;
		private  var _collectionsConfigData:String;
		//加载百分比
		private var _percent:Number;
		public function StreetGameLoader()
		{
			//默认帧频
			stage.frameRate = DEFAULT_FRAMERATE;
			//网页参数
			_flashvars = loaderInfo.parameters;
			//开发者参数初始化
			DeveloperPreferences.init();
			_loaderAssetsList = new Array();
			
			LoaderNewClass = MyStreetLoader_LoaderNew;
			
			
			_loaderNew = new LoaderNewClass();
			this.addChild(_loaderNew);
			_loaderNew.visible=false;
			_loaderNew.addEventListener(Event.ENTER_FRAME,onLoaderFrameEntersFrame,false,0,true);
			_loaderAssetsList.push(_loaderNew);
			
		}
		
		public function get collectionsConfigData():String
		{
			return _collectionsConfigData;
		}

		public function get storeConfigData():String
		{
			return _storeConfigData;
		}

		public function get missionConfigData():String
		{
			return _missionConfigData;
		}

		public function get histroyConfigData():String
		{
			return _histroyConfigData;
		}

		public function get achievementsConfigData():String
		{
			return _achievementsConfigData;
		}

		public function get giftConfigData():String
		{
			return _giftConfigData;
		}

		public function get assetsConfigData():String
		{
			return _assetsConfigData;
		}

		public function get josConfigData():String
		{
			return _josConfigData;
		}

		public function get customersConfigData():String
		{
			return _customersConfigData;
		}

		public function get textConfigData():String
		{
			return _textConfigData;
		}

		public function get goodsConfigData():String
		{
			return _goodsConfigData;
		}

		public function get shopsConfigData():String
		{
			return _shopsConfigData;
		}

		public function get materialsConfigData():String
		{
			return _materialsConfigData;
		}

		public function get partsConfigData():String
		{
			return _partsConfigData;
		}

		public function get flashVars():Object
		{
			return this._flashvars;
		}
		
		/**
		 *卸载资源 
		 * 
		 */		
		public function unloadAssets():void
		{
			var displayObj:DisplayObject;
			while (this._loaderAssetsList.length > 0)
			{
				displayObj = DisplayObject(this._loaderAssetsList.pop());
				removeChild(displayObj);
				displayObj = null;
			}
		}
		/**
		 *加载游戏配置
		 * @param event
		 * 
		 */		
		private function onLoaderFrameEntersFrame(event:Event):void
		{
			if(_loaderNew==null){
				return;
			}
			_loaderNew.removeEventListener(Event.ENTER_FRAME,onLoaderFrameEntersFrame);
			
			_loadingQueue = new LoadingQueue();
			var loadingItem:LoadingQueueItem = new LoadingQueueItem(getGameConfigUrl());
			loadingItem.registerCompleteHandler(this.gameConfigParser);
			loadingItem.registerErrorHandlerHandler(this.gameConfigLoadError);
			_loadingQueue.addItem(loadingItem);
		}
		
		/**
		 *获取游戏配置路径 
		 * @return 
		 * 
		 */		
		private function getGameConfigUrl():String{
			var configURL:String = this.loaderInfo.parameters[GlobalGameConstants.FLASHVARS_CONFIG_URL];
			configURL = configURL ? configURL : GlobalGameConstants.DEFAULT_CONFIG_URL;
			return this.normalizeUrl(configURL, this.getGameAssetsPath());
		}
		/**
		 *解析游戏配置 
		 * 
		 */		
		private function gameConfigParser(event:Event):void
		{
			//游戏配置
			var game_config_xml:XML;
			//部件配置->主要指装饰
			var parts_config_url:String;
			//材料配置
			var materials_config_url:String;
			var shops_config_url:String;
			var goods_config_url:String;
			var text_config_url:String;
			var customers_config_url:String;
			var jobs_config_url:String;
			var assets_config_url:String;
			var gifts_config_url:String;
			var achievements_config_url:String;
			var history_config_url:String;
			var missions_config_url:String;
			var store_config_url:String;
			var collections_config_url:String;
			var gameDataList:XMLList;
			var i:int=0;
			var data_name:String;
			var gameDataItem:LoadingQueueItem;
			
			var flash_vars:Object = loaderInfo.parameters;
			//读取GlobalGameConstants内的默认配置路径
			var defaultXMLURL:String = GlobalGameConstants.DEFAULT_GAME_ASSETS_PATH+GlobalGameConstants.DEFAULT_XML_BASE_URL;
			var defaultSWFURL:String = GlobalGameConstants.DEFAULT_GAME_ASSETS_PATH+GlobalGameConstants.DEFAULT_ASSETS_BASE_URL;
			
			//如果网页参数内有xml基础路径配置则执行如下操作
			if(flash_vars.hasOwnProperty(GlobalGameConstants.FLASHVARS_XML_BASE_URL)){
				defaultXMLURL = flash_vars[GlobalGameConstants.FLASHVARS_XML_BASE_URL];
			}
			//如果网页参数内有swf资源配置路径则执行如下操作
			if(flash_vars.hasOwnProperty(GlobalGameConstants.FLASHVARS_ASSETS_BASE_URL)){
				defaultSWFURL = flash_vars[GlobalGameConstants.FLASHVARS_ASSETS_BASE_URL];
			}
			
			if(flash_vars.hasOwnProperty(GlobalGameConstants.FLASHVARS_GAME_CONFIG)){
				game_config_xml = JSON.decode(GlobalGameConstants.FLASHVARS_GAME_CONFIG);
			}else{
				game_config_xml = new XML(event.target.data);
				parts_config_url = defaultXMLURL + game_config_xml.partsConfig.@src;
				materials_config_url = defaultXMLURL + game_config_xml.materialsConfig.@src;
				shops_config_url = defaultXMLURL + game_config_xml.shopsConfig.@src;
				goods_config_url = defaultXMLURL + game_config_xml.goodsConfig.@src;
				text_config_url = defaultXMLURL+game_config_xml.textContent.@src;
				customers_config_url = defaultXMLURL + game_config_xml.customersConfig.@src;
				jobs_config_url = defaultXMLURL + game_config_xml.jobsConfig.@src;
				assets_config_url = defaultXMLURL + game_config_xml.assetsConfig.@src;
				gifts_config_url = defaultXMLURL + game_config_xml.giftsConfig.@src;
				achievements_config_url = defaultXMLURL + game_config_xml.achievementsConfig.@src;
				history_config_url = defaultXMLURL + game_config_xml.historyConfig.@src;
				missions_config_url = defaultXMLURL + game_config_xml.missionsConfig.@src;
				store_config_url = defaultXMLURL + game_config_xml.storeConfig.@src;
				collections_config_url = defaultXMLURL + game_config_xml.collectionsConfig.@src;
				_gameDataUrlList = new Vector.<String>;
				gameDataList = game_config_xml..gameData;
				i=0;
				while(i<gameDataList.length())
				{
					_gameDataUrlList.push(defaultSWFURL+gameDataList[i].@src);
					i++;
				}
				
			}
			
			this._loadingQueue.parallelLoading=true;
			var parts_config_item:LoadingQueueItem = new LoadingQueueItem(parts_config_url);
			parts_config_item.registerCompleteHandler(this.onPartsConfigLoadingComplete);
			parts_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(parts_config_item);
			
			var materials_config_item:LoadingQueueItem = new LoadingQueueItem(materials_config_url);
			materials_config_item.registerCompleteHandler(this.onMaterialsConfigLoadingComplete);
			materials_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(materials_config_item);
			
			var shops_config_item:LoadingQueueItem = new LoadingQueueItem(shops_config_url);
			shops_config_item.registerCompleteHandler(this.onShopsConfigLoadingComplete);
			shops_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(shops_config_item);
			
			var goods_config_item:LoadingQueueItem = new LoadingQueueItem(goods_config_url);
			goods_config_item.registerCompleteHandler(this.onGoodsConfigLoadingComplete);
			goods_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(goods_config_item);
			
			var text_config_item:LoadingQueueItem = new LoadingQueueItem(text_config_url);
			text_config_item.registerCompleteHandler(this.onTextConfigLoadingComplete);
			text_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(text_config_item);
			
			var customers_config_item:LoadingQueueItem = new LoadingQueueItem(customers_config_url);
			customers_config_item.registerCompleteHandler(this.onCustomersConfigLoadingComplete);
			customers_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(customers_config_item);
			
			var jobs_config_item:LoadingQueueItem = new LoadingQueueItem(jobs_config_url);
			jobs_config_item.registerCompleteHandler(this.onJobsConfigLoadingComplete);
			jobs_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(jobs_config_item);
			
			var assets_config_item:LoadingQueueItem = new LoadingQueueItem(assets_config_url);
			assets_config_item.registerCompleteHandler(this.onAssetsConfigLoadingComplete);
			assets_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(assets_config_item);
			
			var gifts_config_item:LoadingQueueItem = new LoadingQueueItem(gifts_config_url);
			gifts_config_item.registerCompleteHandler(this.onGiftConfigLoadingComplete);
			gifts_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(gifts_config_item);
			
			var achievements_config_item:LoadingQueueItem = new LoadingQueueItem(achievements_config_url);
			achievements_config_item.registerCompleteHandler(this.onAchievementsConfigLoadingComplete);
			achievements_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(achievements_config_item);
			
			var history_config_item:LoadingQueueItem = new LoadingQueueItem(history_config_url);
			history_config_item.registerCompleteHandler(this.onHistoryConfigLoadingComplete);
			history_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(history_config_item);
			
			var missions_config_item:LoadingQueueItem = new LoadingQueueItem(missions_config_url);
			missions_config_item.registerCompleteHandler(this.onMissionConfigLoadingComplete);
			missions_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(missions_config_item);
			
			var store_config_item:LoadingQueueItem = new LoadingQueueItem(store_config_url);
			store_config_item.registerCompleteHandler(this.onStoreConfigLoadingComplete);
			store_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(store_config_item);
			
			var collections_config_item:LoadingQueueItem = new LoadingQueueItem(collections_config_url);
			collections_config_item.registerCompleteHandler(this.onCollectionsConfigLoadingComplete);
			collections_config_item.registerProgressHandler(this.onProgressHandler);
			_loadingQueue.addItem(collections_config_item);
			
			for each (data_name in this._gameDataUrlList) {
				gameDataItem = new LoadingQueueItem(data_name);
				gameDataItem.registerProgressHandler(this.onProgressHandler);
				gameDataItem.registerCompleteHandler(function (event:Event):void{
					_dataLoadedSize += event.currentTarget.bytesTotal;
				})
				this._loadingQueue.addItem(gameDataItem);
			}
			this._loadingQueue.registerCompleteHandler(this.onLoadingQueueComplete);
			
		}
		/**
		 * PartsConfig加载完毕
		 * @param event
		 * 
		 */		
		private function onPartsConfigLoadingComplete(event:Event):void
		{
			_partsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *材料加载完成 
		 * @param event
		 * 
		 */		
		private function onMaterialsConfigLoadingComplete(event:Event):void
		{
			_materialsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *商店配置加载完成 
		 * @param event
		 * 
		 */		
		private function onShopsConfigLoadingComplete(event:Event):void
		{
			_shopsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *货物配置加载完成 
		 * @param event
		 * 
		 */		
		private function onGoodsConfigLoadingComplete(event:Event):void
		{
			_goodsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *Text配置加载完成 
		 * @param event
		 * 
		 */		
		private function onTextConfigLoadingComplete(event:Event):void
		{
			_textConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *顾客配置加载完成 
		 * @param event
		 * 
		 */		
		private function onCustomersConfigLoadingComplete(event:Event):void
		{
			_customersConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 * 职业加载完成
		 * @param event
		 * 
		 */		
		private function onJobsConfigLoadingComplete(event:Event):void
		{
			_josConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *货物Items配置 
		 * @param event
		 * 
		 */		
		private function onAssetsConfigLoadingComplete(event:Event):void
		{
			_assetsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *礼品配置 
		 * @param event
		 * 
		 */		
		private function onGiftConfigLoadingComplete(event:Event):void
		{
			_giftConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *业绩配置 
		 * @param event
		 * 
		 */		
		private function onAchievementsConfigLoadingComplete(event:Event):void
		{
			_achievementsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		
		private function onHistoryConfigLoadingComplete(event:Event):void
		{
			_histroyConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		/**
		 *任务配置数据 
		 * @param event
		 * 
		 */		
		private function onMissionConfigLoadingComplete(event:Event):void
		{
			_missionConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		
		/**
		 *手机商店 
		 * @param event
		 * 
		 */		
		private function onStoreConfigLoadingComplete(event:Event):void
		{
			_storeConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		
		private function onCollectionsConfigLoadingComplete(event:Event):void
		{
			_collectionsConfigData = event.currentTarget.data;
			_dataLoadedSize+=event.currentTarget.data.length;
		}
		
		private function onProgressHandler(event:ProgressEvent):void
		{
			//trace("has been loaded-> "+this._dataLoadedSize+" Total bytes-> "+ dataLoadedTotal);
			_percent = this._dataLoadedSize/dataLoadedTotal;
			_percent = Math.min(_percent,1);
			
		}
		/**
		 *队列加载完毕 
		 * 
		 */		
		private function onLoadingQueueComplete():void
		{
			this._loadingQueue.parallelLoading = false;
			this._loadingQueue.registerCompleteHandler(null);
			var loadingItem:LoadingQueueItem = new LoadingQueueItem(this.getGameSwfUrl());
			loadingItem.registerCompleteHandler(this.onGameSwfLoaded);
			loadingItem.registerProgressHandler(this.onProgressHandler);
			this._loadingQueue.addItem(loadingItem);
		}
		
		/**
		 * 标准化路径
		 * @param fileName
		 * @param basePath
		 * @return 
		 * 
		 */		
		private function normalizeUrl(url:String,basePath:String):String{
			if (!(url.substring(0, 7) == "http://") && !(url.substring(0, 8) == "https://")){
				return ((basePath + url));
			}
			return url;
		}
		
		/**
		 *获取资源路径(包括配置以及素材)
		 * @return 
		 * 
		 */		
		private function getGameAssetsPath():String{
			var basePath:String = this.loaderInfo.parameters[GlobalGameConstants.FLASHVARS_GAME_BASE_PATH];
			basePath = basePath ? basePath : GlobalGameConstants.DEFAULT_GAME_ASSETS_PATH;
			return basePath;
		}
		
		private function getGameSwfUrl():String{
			var maiSWFURL:String = this.loaderInfo.parameters[GlobalGameConstants.FLASHVARS_GAME_SWF_URL];
			maiSWFURL = (maiSWFURL) ? maiSWFURL : GlobalGameConstants.DEFAULT_GAME_SWF_URL;
			return this.normalizeUrl(maiSWFURL, "");
		}
		
		private function onGameSwfLoaded(event:Event):void
		{
			trace("gameSWF Loaded");
			IApplication(event.currentTarget.content).start(this);
			this.addChild(event.currentTarget.content);
			
		}
		
		/**
		 *游戏配置加载错误处理 
		 * @param event
		 * 
		 */		
		private function gameConfigLoadError(event:Event):void{
			trace("游戏配置加载错误!"+event);
		}
	}
}